package com.northone.statistics.fragment;

import java.lang.reflect.Field;

import com.northone.statistics.BaseFragment;
import com.northone.statistics.R;
import com.northone.statistics.activity.AddSaintActivity;
import com.northone.statistics.adapter.SaintCursorAdapter;
import com.northone.statistics.database.SaintDataBaseHelper;
import com.northone.statistics.utils.Constans;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;

public class SaintFragment extends BaseFragment implements OnClickListener {
	private static final int REQUEST_CODE_SAINTINFO = 0453;
	private ImageView iv_header, iv_add, iv_search;
	private View view;
	private SearchView searchView;
	private ListView lv_saint;
	// 查询数据库得到的结果集 。
	public Cursor cursor, cursor_like;
	private SaintCursorAdapter saintAdapter;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constans.QUERY_ALL_SAINT:
				cursor = (Cursor) msg.obj;
				saintAdapter.changeCursor(cursor);
				break;
			case Constans.SEARCH_SAINT:
				cursor_like = (Cursor) msg.obj;
				saintAdapter.changeCursor(cursor_like);
				break;
			default:
				break;
			}

		};
	};

	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_saint, null);
		initTitleBar();
		initView();
		return view;
	}

	private void initTitleBar() {
		iv_header = (ImageView) view.findViewById(R.id.iv_lefticon);
		iv_add = (ImageView) view.findViewById(R.id.iv_add);
		iv_search = (ImageView) view.findViewById(R.id.iv_search);
		iv_add.setImageResource(R.drawable.saint_titlebar_add_selector);
		iv_search.setImageResource(R.drawable.saint_titlebar_search_selector);
		iv_add.setVisibility(View.VISIBLE);
		iv_search.setVisibility(View.VISIBLE);

		TextView tv_saint = (TextView) view.findViewById(R.id.tv_title);
		String title = getResources().getString(R.string.saint);
		tv_saint.setText(title);

		iv_header.setOnClickListener(this);
		iv_add.setOnClickListener(this);
		iv_search.setOnClickListener(this);
	}

	private void initView() {
		lv_saint = (ListView) view.findViewById(R.id.lv_saint);
		// 设置ListView启用过滤 。
		lv_saint.setTextFilterEnabled(true);
		// 在子线程中查询所有的圣徒，通过Handler传递给UI线程 。
		cursor = application.database.query(SaintDataBaseHelper.TABLE_NAME_BASE, null, null, null, null, null, null);
		saintAdapter = new SaintCursorAdapter(activity, cursor, true, application.database);
		lv_saint.setAdapter(saintAdapter);

		searchView = (SearchView) view.findViewById(R.id.search_saint);
		// 设置该searchView是否自动缩小为图标 。
		searchView.setIconifiedByDefault(false);
		// 设置该searchView显示搜索按钮 。
		searchView.setSubmitButtonEnabled(true);
		// 设置该searchView默认显示的提示文本 。
		searchView.setQueryHint("请输入圣徒的姓名！");
		// 表示在内容为空时不显示取消的x按钮，内容不为空时显示.
		// searchView.onActionViewExpanded();
		// 设置该searchView焦点更改时的监听器 。
		searchView.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// 如果searchView获取焦点了就将底部的RadioGroup隐藏掉 ,如果searchView失去焦点了则将其显示出来
				activity.getBottomRadioGroup().setVisibility(hasFocus ? View.GONE : View.VISIBLE);
			}
		});
		try {
			// 通过反射，修改默认的样式，可以从android的search_view.xml中找到需要的组件
			Field field = searchView.getClass().getDeclaredField("mSubmitButton");
			field.setAccessible(true);
			ImageView iv = (ImageView) field.get(searchView);
			iv.setImageDrawable(this.getResources().getDrawable(R.drawable.saint_search_selector));

		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		// 设置事件监听器 。
		searchView.setOnQueryTextListener(new OnQueryTextListener() {
			@Override
			public boolean onQueryTextSubmit(String query) {
				cursor_like = application.database.query(SaintDataBaseHelper.TABLE_NAME_BASE, null, "name LIKE ? ",
						new String[] { "%" + query.trim() + "%" }, null, null, null);
				saintAdapter.changeCursor(cursor_like);
				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				if (TextUtils.isEmpty(newText)) {
					cursor = application.database.query(SaintDataBaseHelper.TABLE_NAME_BASE, null, null, null, null,
							null, null);
					saintAdapter.changeCursor(cursor);
					// 清除ListView的过滤 。
					lv_saint.clearTextFilter();
				} else {
					// 根据条件模糊查询数据库数据
					cursor_like = application.database.query(SaintDataBaseHelper.TABLE_NAME_BASE, null, "name LIKE ? ",
							new String[] { "%" + newText.trim() + "%" }, null, null, null);
					saintAdapter.changeCursor(cursor_like);
					// 使用输入的内容对ListView的列表项进行过滤 。
					// lv_saint.setFilterText(newText);
				}
				return true;
			}
		});

		lv_saint.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
				//TODO
			}
		});
		lv_saint.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				//TODO
				return false;
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_CANCELED) {
			return;
		}
		switch (requestCode) {
		case REQUEST_CODE_SAINTINFO:
			cursor = application.database.query(SaintDataBaseHelper.TABLE_NAME_BASE, null, null, null, null, null,
					null);
			saintAdapter.changeCursor(cursor);
			break;
		default:
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_lefticon:
			break;
		case R.id.iv_add:
			startActivityForResult(new Intent(activity, AddSaintActivity.class), REQUEST_CODE_SAINTINFO);
			break;
		case R.id.iv_search:
			searchView.setVisibility(searchView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
			if (searchView.getVisibility() == View.GONE) {
				cursor = application.database.query(SaintDataBaseHelper.TABLE_NAME_BASE, null, null, null, null, null,
						null);
				saintAdapter.changeCursor(cursor);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (cursor != null) {
			cursor.close();
		}
		if (cursor_like != null) {
			cursor_like.close();
		}
	}

	@Override
	public void onDetach() {
		super.onDetach();
		try {
			Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
			childFragmentManager.setAccessible(true);
			childFragmentManager.set(this, null);
		} catch (NoSuchFieldException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}
